<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Backstage\User\CreateRequest;
use App\Http\Requests\Backstage\User\UpdateRequest;
use App\Models\User;
use App\Transformers\UserTransformer;

class UserController extends BaseController
{
    public function index()
    {
        $page = get_request_page();
        if ($page) {
            $users = User::paginate($page);
            return $this->response->paginator($users, new UserTransformer());
        }
    }

    /**
     * @param CreateRequest $request
     * @return mixed
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            if (isset($attributes['password'])) {
                $attributes['password'] = bcrypt($attributes['password']);
            }
            $model = User::create($attributes);
            return $model;
        });
        $location = dingo_route('v1', 'backstage.users.show', $model->id);
        return $this->response->item($model, new UserTransformer())
            ->withHeader('Location', $location)
            ->setStatusCode(201);
    }

    /**
     * @param UpdateRequest $request
     * @param $id
     * @return \Dingo\Api\Http\Response
     * @throws \Throwable
     */
    public function update(UpdateRequest $request, $id)
    {
        \DB::transaction(function () use ($request, $id) {
            $attributes = $request->validated();
            if (isset($attributes['password'])) {
                $attributes['password'] = bcrypt($attributes['password']);
            }
            $user = User::whereId($id)->firstOrFail();
            $model = $user->update($attributes);
            return $model;
        });
        return $this->response->noContent();
    }

    public function destroy($id)
    {
        if ($user = User::whereId($id)->first()) {
            $user->delete();
        }
        return $this->response->noContent();
    }
}
